
package com.kanjian.music.network;

import java.util.Date;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.Loader;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.kanjian.music.api.RequestEntity;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.database.DaoMaster;
import com.kanjian.music.database.DaoMaster.DevOpenHelper;
import com.kanjian.music.database.DaoSession;
import com.kanjian.music.database.DatabaseManager;
import com.kanjian.music.entity.RequestCache;
import com.kanjian.music.util.CommonUtil;
import com.kanjian.music.volley.VolleyQueue;

/**
 * 基础网络加载类 提供公共异常等信息
 * 
 * @author xuyanjun
 */
public class HttpLoader extends Loader<String> {

    public RequestEntity mEntity;

    public Exception mFailReason;
    
    private boolean isLoaded;

    public HttpLoader(Context context) {
        super(context);
    }

    public HttpLoader(Context context, Bundle args) {
        super(context);
        mEntity = (RequestEntity) args.get(IntentConstants.HTTPLOADERREQUESTPARAM);
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        if (!isLoaded) {
            forceLoad();
        }
    }

    @Override
    protected void onForceLoad() {
        super.onForceLoad();
        loadInBackground();
    }
    
    public void loadInBackground() {
        VolleyQueue.getRequestQueue().add(
                new StringRequest(mEntity.mMethod, mEntity.mUrl, new Listener<String>() {
                    @Override
                    public void onResponse(String arg0) {
                        DatabaseManager.session.getRequestCacheDao().insertOrReplace(
                                new RequestCache(mEntity.mUrl, arg0, new Date(), new Date()));
                        deliverResult(arg0);
                        isLoaded = true;
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        mFailReason = arg0;
                        CommonUtil.processNetWorkError(getContext(), arg0);
                        deliverResult(null);
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        return mEntity.mParams;
                    }

                    protected Response<String> parseNetworkResponse(NetworkResponse response) {
                        return super.parseNetworkResponse(response);
                    }

                });
    }

}
